package com.zhuiyun.project.api.system.user.controller;

import com.zhuiyun.project.annotation.OptLog;
import com.zhuiyun.project.api.system.user.entity.SysUser;
import com.zhuiyun.project.api.system.user.service.SysProfileService;
import com.zhuiyun.project.api.system.user.service.SysUserService;
import com.zhuiyun.project.common.controller.BaseController;
import com.zhuiyun.project.common.errorCode.CommonException;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.security.jwt.JWTConfig;
import com.zhuiyun.project.utils.*;
import com.zhuiyun.project.utils.constants.CommonConstants;
import com.zhuiyun.project.utils.uuid.Seq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;

import static com.zhuiyun.project.utils.SecurityUtils.getLoginName;

/**
 * @ClassName SysProfileController
 * @Description TODO
 * @Author lzy
 * @Date 2023/8/2 11:11
 **/
@RestController
@RequestMapping("/system/profile")
@Api(tags = "个人信息")
@Slf4j
public class SysProfileController extends BaseController {

    @Resource
    SysUserService sysUserService;

    @Resource
    SysProfileService sysProfileService;

    @ApiOperation(value = "获取用户个人信息")
    @OptLog(modular = "个人信息", type = CommonConstants.SELECT, describe = "select")
    @GetMapping("/getUserProfile")
    public CommonResult getUserProfile(){
        SysUser loginUser = getLoginUser();
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("profile", loginUser);
        objectObjectHashMap.put("roleGroup", sysUserService.selectUserRoleGroup(getLoginName()));
        return CommonResult.ok(objectObjectHashMap);
    }

    /**
    * @Description 吸怪密码
    * @Author lzy
    * @Date 2023/8/2 11:37
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param oldPassword
    * @param newPassword
    */
    @ApiOperation(value = "修改密码")
    @OptLog(modular = "个人信息", type = CommonConstants.UPDATE, describe = "修改方法")
    @PutMapping("/updatePwd")
    public CommonResult updatePwd(String oldPassword, String newPassword){
        SysUser loginUser = getLoginUser();
        Integer id = loginUser.getId();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return CommonResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return CommonResult.error("新密码不能与旧密码相同");
        }
        if (sysUserService.resetUserPwd(id, SecurityUtils.encryptPassword(newPassword)) > 0) {
            // 更新缓存用户密码
            loginUser.setPassword(SecurityUtils.encryptPassword(newPassword));
            String token = (String) RedisUtil.get(getLoginName());
            // 设置token过期时间
            RedisUtil.set(token,loginUser, JWTConfig.expiration);
            return CommonResult.ok(EmErrorCode.UPDATE_OK);
        }
        return CommonResult.error("修改密码异常，请联系管理员");
    }

    /**
    * @Description 修改个人基本信息
    * @Author lzy
    * @Date 2023/8/2 14:24
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param sysUser
    */
    @ApiOperation(value = "修改基本信息")
    @OptLog(modular = "个人信息", type = CommonConstants.UPDATE, describe = "修改方法")
    @PutMapping("/updateProfile")
    public CommonResult updateProfile(@RequestBody SysUser sysUser) throws CommonException {
        SysUser loginUser = getLoginUser();
        sysUser.setId(getUserId());
        sysUser.setUpdateBy(getLoginName());
        sysUser.setUpdateTime(new Date());
        sysUser.setPassword(null);
        sysUser.setAvatarId(null);
        int i = sysUserService.updateProfile(sysUser);
        if (i > 0) {
            loginUser.setUserName(sysUser.getUserName());
            loginUser.setPhone(sysUser.getPhone());
            loginUser.setEmail(sysUser.getEmail());
            loginUser.setSex(sysUser.getSex());
            String token = (String) RedisUtil.get(getLoginName());
            // 设置token过期时间
            RedisUtil.set(token,loginUser, JWTConfig.expiration);
            return CommonResult.ok(EmErrorCode.UPDATE_OK);
        } else {
            return CommonResult.error(EmErrorCode.UPDATE_ERROR);
        }
    }

    /**
    * @Description 修改用户头像
    * @Author lzy
    * @Date 2023/8/4 16:22
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param file
    */
    @PostMapping(value = "/avatar")
    public CommonResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        SysUser loginUser = getLoginUser();
        String avatarId = UploadFileUtils.uploadAvatar(file);
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("avatarId", avatarId);
        if (avatarId != null && !avatarId.isEmpty()) {
            int i = sysUserService.updateAvatarId(avatarId, loginUser.getId());
            if (i > 0) {
                loginUser.setAvatarId(avatarId);
                String token = (String) RedisUtil.get(getLoginName());
                // 设置token过期时间
                RedisUtil.set(token,loginUser, JWTConfig.expiration);
                return CommonResult.ok(objectObjectHashMap);
            } else {
                return CommonResult.error(EmErrorCode.UPDATE_ERROR);
            }
        } else {
            return CommonResult.error(EmErrorCode.UPDATE_ERROR);
        }
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file)
    {
        return StringUtils.format("{}_{}.{}",
                FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), getExtension(file));
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file)
    {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension))
        {
            extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }




}
